<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-button @click="addVisible=true">添加分类</el-button>
      </el-col>
      <el-col :span="6">
        <el-button @click="getNextLevelType">进入下一个类</el-button>
      </el-col>
      <el-col :span="6">
        <el-button @click="getLastLevelType">返回</el-button>
      </el-col>
    </el-row>

    <!--表格主体 -->
    <el-table :data="tableData" style="width: 80%" border>
      <el-table-column label="标签id" width="180" prop="typeId"></el-table-column>
      <el-table-column label="标签名称" width="180" prop="typeName"></el-table-column>
      <el-table-column label="标签等级" width="180" prop="typeLevel"></el-table-column>
      <el-table-column label="排序值" width="180" prop="typeRank"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" @click="getChildrens(scope.$index, scope.row)">子分类</el-button>
          <el-button size="mini" @click="handleDelete(scope.$index,scope.row.typeId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      :total="tempData.length"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <div class="block">
      <span class="demonstration">hover 触发子菜单</span>
      <el-cascader
        v-model="value"
        :options="options"
        :props="{ expandTrigger: 'hover',checkStrictly: true  }"
        @change="handleChange"
      ></el-cascader>
    </div>

    <el-dialog title="添加商品分类" :visible.sync="addVisible" width="30%">
      <el-form
        :model="addForm"
        :rules="rules"
        ref="addForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="分类名称" prop="typeName">
          <el-input v-model="addForm.typeName"></el-input>
        </el-form-item>
        <el-form-item label="父分类">
          <el-cascader
            v-model="addForm.typeParentId"
            :options="options"
            ref="cascader"
            :props="{ expandTrigger: 'hover',checkStrictly: true  }"
            @change="setParentId"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="分类排序值" prop="typeRank">
          <el-input v-model="addForm.typeRank"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitAddForm('addForm')">添加标签</el-button>
          <el-button @click="resetForm('addForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="编辑分类" :visible.sync="editVisible" width="30%">
      <el-form
        :model="editForm"
        :rules="rules"
        ref="editForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="分类名称" prop="typeName">
          <el-input v-model="editForm.typeName"></el-input>
        </el-form-item>
        <el-form-item label="分类排序值" prop="typeRank">
          <el-input v-model="editForm.typeRank"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitEditForm('editForm')">修改标签</el-button>
          <el-button @click="resetForm('editForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllType,
  addGoodType,
  getCurrentLevel,
  getChidrenType,
  UpdateType,
  delGoodType,
} from "@/api/goodtype";
export default {
  data() {
    return {
      value: [],

      options: [],

      // 控制添加标签表单显示
      addVisible: false,
      // 控制编辑表单的显示
      editVisible: false,

      //当前编辑的索引
      index: "",

      //表格数据
      tableData: [],

      //全部数据
      tempData: [],

      //添加表单
      addForm: {
        typeName: "",
        // 没有添加默认为0
        typeParentId: 0,
        typeRank: "",
      },

      //编辑表单
      editForm: {
        typeId: "",
        typeName: "",
        typeRank: "",
      },

      // 当前标签等级
      currentLevel: 1,

      rules: {
        typeName: [
          { required: true, message: "标签名称为空", trigger: "blur" },
        ],

        typeRank: [{ required: true, message: "排序值", trigger: "blur" }],
      },

      //分类选择器
      value: [],

      options: [],

      // 当前页
      currentPage: 1,
      // 当前页面大小
      pageSize: 5,
    };
  },
  methods: {
    handleChange(value) {
      console.log(value);
    },

    init() {
      // 加载所有标签
      getAllType().then((res) => {
        var data = res.data;
        // 遍历父节点进行删除children  in 遍历拿数组索引 of 遍历 拿数组对象

        for (var item of data) {
          console.log(item);
          this.removeChildren(item);
        }
        this.options = data;

        this.options = res.data;
      });

      // 加载当前等级标签
      getCurrentLevel(this.currentLevel).then((res) => {
        this.tableData = res.data;
        this.tempData = res.data;
      });
    },

    //去除树型结构的children树型 参数为父节点
    removeChildren(node) {
      // 假设没有长度 或children 长度为0 删除该属性
      if (!node.children || !node.children.length) {
        delete node.children;
        // 要记得返回不然报错
        return;
      }

      // 遍历children 继续删除
      for (var item of node.children) {
        this.removeChildren(item);
      }

      return node;
    },

    //设置父节点
    setParentId(val) {
      this.addForm.typeParentId = val[0];
    },

    submitAddForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.$refs.cascader.getCheckedNodes(true));

          this.addForm.typeParentId = this.$refs.cascader.getCheckedNodes(
            true
          )[0].data.value;

          //添加标签进行刷新
          addGoodType(this.addForm).then((res) => {
            if (res.code == 200) {
              //重新加载数据
              this.init();
              // 清空输入
              this.addForm.typeParentId = 0;
              this.addForm.typeName = "";
              this.addForm.typeRank = "";
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //提交编辑表单
    submitEditForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //对标签进行更新
          UpdateType(this.editForm).then((res) => {
            if (res.code == 200) {
              this.tableData[this.index].typeName = this.editForm.typeName;
              this.tableData[this.index].typeRank = this.editForm.typeRank;
              this.tempData[this.index].typeName = this.editForm.typeName;
              this.tempData[this.index].typeRank = this.editForm.typeRank;
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
      //重置级联选择器
      this.addForm.typeParentId = 0;
    },

    //进入下一个等级的标签
    getNextLevelType() {
      //当前标签等级+1
      this.currentLevel++;
      getCurrentLevel(this.currentLevel).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data;
          this.tempData = res.data;
        }
      });
    },

    //返回上一个等级的标签
    getLastLevelType() {
      //判断是否返回最上一层
      if (this.currentLevel == 1) {
        this.$message({
          type: "info",
          message: "已经返回到最上一层了",
        });
        return;
      }

      this.currentLevel--;
      getCurrentLevel(this.currentLevel).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data;
          this.tempData = res.data;
        }
      });
    },

    //获取父分类的子分类
    getChildrens(index, row) {
      getChidrenType(row.typeId).then((res) => {
        if (res.code == 200) {
          //当前标签等级+1
          this.currentLevel++;
          this.tableData = res.data;
          this.tempData = res.data;
        }
      });
    },

    //更新商品标签
    handleEdit(index, row) {
      this.editVisible = true;
      this.editForm = row;
      this.index = index;
    },
    // 删除标签
    handleDelete(index, id) {
      this.$confirm("此操作将永久删除该标签, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delGoodType(id).then((res) => {
            if (res.code == 200) {
              let data = [];
              for (let item of this.tempData) {
                if (item.typeId == id) {
                  console.log("删除了");
                  continue;
                }
                data.push(item);
              }
              this.tempData = data;

              this.tableData = this.tempData.slice(
                this.currentPage - 1,
                this.pageSize
              );
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.tableData = this.tempData.slice(this.currentPage - 1, this.pageSize);
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.tableData = this.tempData.slice(this.currentPage - 1, this.pageSize);
    },
  },
  created() {
    this.init();
  },
};
</script>

<style>
</style>